<?php

namespace app\admin\controller;

use app\common\controller\Base64;
use app\common\controller\Log;
use app\common\model\user\Users;
use think\Controller;
use think\Db;
use think\Exception;
use think\Loader;

class User extends Base {
	/**
	 * 用户列表
	 *
	 * @return unknown
	 */
	public function userList() {
		$data = $this->request->post ( '' );
		$depart = new Depart ();
		$where = [ 
				'state' => [ 
						'neq',
						0 
				] 
		];
		if (! empty ( $data ['real_name'] )) {
			$real_name = $data ['real_name'];
			$where ['real_name'] = [ 
					'like',
					"%{$real_name}%" 
			];
		}
		if (! empty ( $data ['time_arr'] )) {
			$where ['create_time'] = [ 
					'between',
					[ 
							strtotime ( $data ['time_arr'] [0] ),
							strtotime ( $data ['time_arr'] [1] ) 
					] 
			];
		}
		if (! empty ( $data ['tjuser'] )) {
			$where['tjuser'] = $data['tjuser'];
		}
		if (! empty ( $data ['mobile'] )) {
			$where ['mobile'] = $data ['mobile'];
		}
		
		$list = Users::where ( $where )->order ( 'id desc' )->field ( 'id,real_name,no,mobile,user_name,state,tjuser,idcard,create_time,update_time,is_lock,is_cert,idcard_up,idcard_down,is_act' )->paginate ()->toArray ();
		foreach ($list['data'] as &$rows) {
			$rows['tjuser_name'] = Users::where(['no' => $rows['tjuser']])->value('user_name');
		}
		return jsonSuccess ( $list );
	}
	
	/**
	 * 添加员工
	 *
	 * @throws Exception
	 * @return unknown
	 */
	public function addUser() {
		$data = $this->request->post ( '' );
		Db::startTrans ();
		try {
			//验证信信息合法性
			$count = Users::count();
			if(!$data['user_name'])throw new Exception('请输入登录账号');
			if(!$data['real_name'])throw new Exception('请输入真实姓名');
			if($data['tjuser']){
				$tjuser_id = Users::where(['no' => $data['tjuser']])->value('id');
				if(!$tjuser_id)
					throw new Exception('推荐人不存在');
					$data['act_id'] = $this->findAct($tjuser_id);
			}else{
				$data['tjuser'] = '';
			}
			if(!$data['mobile'])throw new Exception('请输入手机号码');
			if(!$data['password'])throw new Exception('请输入登录密码');
			if(!$data['pay_pwd'])throw new Exception('请输入交易密码');
			if(Users::where(['user_name' => $data['user_name']])->value('id'))
				throw new Exception('用户账号已被注册');
			//重新组装数据
			$data ['password'] = md5 ( $data ['password'] );
			$data ['pay_pwd'] = md5 ( $data ['pay_pwd'] );
			$data ['create_time'] = time ();
			$data ['update_time'] = time ();
			$data['no'] = 'no'.(10000 + $count);
			// 验证数据是否冲突
			if ($data ['no'] && Users::where ( [ 
					'no' => $data ['no'],
					'state' => [ 
							'neq',
							0 
					] 
			] )->value ( 'id' ))
				throw new Exception ( '该员工编号已存在' );
			if (Users::where ( ['mobile' => $data ['mobile'] ] )->value ( 'id' ))
				throw new Exception ( '手机号码已被使用' );
			// 添加数据
			Users::create ( $data );
			// 添加日志
			Log::addLog ( 1, '添加会员【' . $data ['real_name'] . '】' );
			Db::commit ();
		} catch ( Exception $e ) {
			Db::rollback ();
			return jsonError ( $e->getMessage () );
		}
		return jsonSuccess ( '添加会员成功' );
	}
	
	public function findAct($user_id)
	{
		$user = Users::get($user_id);
		if($user->is_act) {
			return $user_id;
		}else{
			$tjuser_id = Users::where(['no' => $user->tjuser])->value('id');
			return $this->findAct($tjuser_id);
		}
	}
	
	/**
	 * 修改会员状态
	 *
	 * @throws Exception
	 * @return unknown
	 */
	public function leaveUser() {
		$id = $this->request->post ( 'id' );
		Db::startTrans ();
		try {
			$user = Users::get ( $id );
			if($user->state == 0)throw new Exception('状态错误');
			$state = $user->state == 1 ? 2 : 1;
			$msg = $user->state == 1 ? '停用会员' : '启用会员';
			$user->save(['state' => $state ,'update_time' => time()]);
			// 添加日志
			Log::addLog ( 2, "{$msg}【{$user->user_name}】" );
			Db::commit ();
		} catch ( Exception $e ) {
			Db::rollback ();
			return jsonError ( $e->getMessage () );
		}
		return jsonSuccess ( "{$msg}成功" );
	}
	
	/**
	 * 获取员工信息
	 *
	 * @return unknown
	 */
	public function getUserInfo() {
		$depart = new Depart ();
		$id = $this->request->post ( 'id' );
		$info = Users::get ( $id );
		$info->password = '';
		$info->pay_pwd = '';
		return jsonSuccess ( $info );
	}
	
	/**
	 * 修改员工信息
	 *
	 * @throws Exception
	 * @return unknown
	 */
	public function updateUser() {
		$data = $this->request->post ( '' );
		$user = Users::get ( $data ['id'] );
		Db::startTrans ();
		try {
			//验证信信息合法性
			$count = Users::count();
			unset($data['user_name']);
			if(!$data['user_name'])throw new Exception('请输入登录账号');
			if(!$data['real_name'])throw new Exception('请输入真实姓名');
			if($user -> id == 1 && $data['tjuser'])throw new Exception('第一个会员不能更改推荐人');
			if($count){
				if(!$data['tjuser'])
					throw new Exception('请输入推荐人编号');
					if(!Users::where(['no' => $data['tjuser']])->value('id'))
						throw new Exception('推荐人不存在');
			}else{
				$data['tjuser'] = '';
			}
			if(!$data['mobile'])throw new Exception('请输入手机号码');
			if(!$data['password'])unset($data['password']);
			else $data ['password'] = md5 ( $data ['password'] );
			if(!$data['pay_pwd'])unset($data['pay_pwd']);
			else $data ['pay_pwd'] = md5 ( $data ['pay_pwd'] );
			//重新组装数据
			$data ['update_time'] = time ();
			$user->save ( $data );
			// 添加日志
			Log::addLog ( 2, "修改会员【{$user->real_name}】" );
			Db::commit ();
		} catch ( Exception $e ) {
			Db::rollback ();
			return jsonError ( $e->getMessage () );
		}
		return jsonSuccess ( '修改成功' );
	}
	
	/**
	 * 锁定解锁用户
	 * @return unknown
	 */
	public function lockUser()
	{
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$user = Users::get($id);
			$lock = $user->is_lock ? 0 : 1;
			$user->save(['update_time' => time(),'is_lock' => $lock]);
			//添加日志
			$msg = $user->is_lock ? "解锁用户【{$user->user_name}】" : "锁定用户【{$user->user_name}】";
			Log::addLog(2, $msg);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('设置成功');
	}
	
	/**
	 * 实名认证
	 * @throws Exception
	 * @return unknown
	 */
	public function trueIdcard()
	{
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$user = Users::get($id);
			if(!$user->idcard || !$user->idcard_up || !$user->idcard_down)
				throw new Exception('身份信息不完整');
			$user->save(['update_time' => time(),'is_cert' => 1]);
			//添加日志
			Log::addLog(2, "实名认证用户【{$user->user_name}】");
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('实名认证成功');
	}
	
	/**
	 * 设置为代理
	 * @return unknown
	 */
	public function isAct()
	{
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$user = Users::get($id);
			if($user->is_act)return jsonError('状态错误');
			$user->save(['is_act' => 1,'update_time' => time()]);
			//获取所有下级ID
			$id_arr = $this->getDown($id);
			//更改下级ID的代理
			Users::where(['id' => ['in',$id_arr]])->update(['act_id' => $id]);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('设置成功');
	}
	/**
	 * 代理互转
	 * @return unknown
	 */
	public function transition()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			$user_id = Users::where(['user_name' => $data['user_name']])->field('id,is_act,no')->find();
			if(!$user_id['is_act'])return jsonError('请输入正确的代理账号');
			$user_arr = Users::where(['tjsuer' => $user_id['no']])->column('id');
			$user_id = $user_id['id'];
			$accept_id = Users::where(['user_name' => $data['accept_name']])->field('id,is_act')->find();
			if(!$accept_id['is_act'])return jsonError('请输入正确的代理账号');
			//获取转出代理的所有用户
			$user_ids = Users::where(['act_id' => $user_id])->column('id');
			//转入
			$res = Users::where(['id' => ['in',$user_arr]])->update(['tjuser' => $accept_id['no']]);
			$accept_id = $accept_id['id'];
			$res = Users::where(['id' => ['in',$user_ids]])->update(['act_id' => $accept_id]);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('设置成功');
	}
	
	/**
	 * 修改邀请人
	 * @return unknown
	 */
	public function tjTransition()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			//获取待转出邀请人的下级会员
			$out_user = Users::where(['user_name' => $data['user_name']])->field('id,is_act,no')->find();
			if(!$out_user)throw new Exception('转出人不存在');
			$down_user_ids = Users::where(['tjuser' => $out_user['no']])->column('id');
			//获取所有下级会员ID数组
			$down_all_user = $this->getDown($out_user['id']);
			//获取待转入会员
			$in_user = Users::where(['user_name' => $data['accept_name']])->field('id,is_act,no,act_id')->find();
			if(!$in_user)throw new Exception('转入人不存在');
			if(in_array($in_user['id'], $down_all_user))throw new Exception('无法和下级互转');
			$act_id = $in_user['is_act'] ? $in_user['id'] : $in_user['act_id'];
			Users::where(['id' => ['in',$down_user_ids]])->update([
					'update_time' => time(),
					'tjuser' => $in_user['no'],
					'act_id' => $act_id
			]);
			Db::commit();
		}catch (Exception $e){
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('互转成功');
	}
	/**
	 * 获取所有下级ID
	 * @param unknown $user_id
	 * @param array $arr
	 * @return array
	 */
	private function getDown($user_id,$arr = [])
	{
		$user_id = is_array($user_id) ? $user_id : [$user_id];
		$no_arr = Users::where(['id' => ['in',$user_id]])->column('no');
		$id_arr = Users::where(['tjuser' => ['in',$no_arr]])->column('id');
		if($id_arr) {
			$arr = array_merge($arr,$id_arr);
			return $this->getDown($id_arr,$arr);
		}else{
			return $arr;
		}
	}
}